﻿
Ext.ns('FuelSensorList');
FuelSensorList.version = 'Beta 1';
var g_FuelSensorWindowObject=null;

function trackerFuelSensorWin(autoload){
    function msgUpdateSuccess() {
        Ext.MessageBox.buttonText.ok = _CustomerConfigResource_OK;
        Ext.Msg.show({
            title: _CustomerConfigResource_Tip,
            msg: _CustomerConfigResource_Success,
            buttons: Ext.Msg.OK,
            animEl: 'elId',
            icon: Ext.MessageBox.INFO
        });
    };
    
    function msgUpdateFailure() {
        Ext.MessageBox.buttonText.ok = _CustomerConfigResource_OK;
        Ext.Msg.show({
            title: _CustomerConfigResource_Tip,
            msg: _CustomerConfigResource_Failure,
            buttons: Ext.Msg.OK,
            animEl: 'elId',
            icon: Ext.MessageBox.WARNING
        });
    }
    
    var pagesize = 65535;
    var fuelsensorfield = [{name:"choosed",type:"boolean"},"id", "sssid", "trackername","fuel_sensor_name",{name:"fuel_sensor_id",type:"integer"},{name:"tanksize",type:"integer"},{name:"high_alarm_percent",type:"integer"},{name:"flow_alarm_percent",type:"integer"},{name:"low_alarm_percent",type:"integer"},"lasttime","lastvalue",'btnQuickReport'];
    
    
    
    var trackNameCombo = getTrackerCheckboxCombo(true);
    
    var fuelsensorstore = new Ext.data.GroupingStore({
	   proxy:new Ext.data.HttpProxy({
            url:"HandlerSearchFuelSensor",
            method:"POST",
            timeout:120000
       }),
       reader:new Ext.data.JsonReader({
			fields:fuelsensorfield,
            root:"data",
            totalProperty: "totalCount"
       }),
       sortInfo:{field: 'trackername', direction: "ASC"}
   });
 
    function sensorNameFromSensorId(sensorid){
        if(sensorid == 0)
            return _TrackerMain_Null;
        else if(sensorid==1)
           return _TrackerMain_FuelC;
        else if(sensorid ==2)
           return _TrackerMain_FuelR;
        else if(sensorid == 3)
           return _TrackerMain_FuelSensorV1;
    }
    
    function sensorIdFromSensorName(sensorName){
        if(sensorName == _TrackerMain_Null)
            return 0;
        else if(sensorName == _TrackerMain_FuelC)
            return 1;
        else if(sensorName == _TrackerMain_FuelR)
            return 2;
        else if(sensorName == _TrackerMain_FuelSensorV1)
            return 3;
    }
    
    
   fuelsensorstore.addListener('load', function(store, records) {
        store.each(function(record){
            var sensorid= record.get('fuel_sensor_id');
            record.set('fuel_sensor_name',sensorNameFromSensorId(sensorid));
        });
        
        lastlocationintervalstore.each(function(r){
            for(t in r.json){
                var fname = t;
                if(fname =='01FF'){
                    var v = r.json[t];
                    var index = fuelsensorstore.findExact('sssid',r.get('sssid'));
                    if(index != -1){
                        var record = fuelsensorstore.getAt(index);
                        record.set('lasttime',r.get('receivedtime'));
                        record.set('lastvalue',(v*100).toFixed(2)+"%");
                    }
                }
            }
        });
   });
   
   
   
   var btnSelectAll = new Ext.Button({
        text: _Photo_SelectAll,
        style: 'margin-right:16px',
        width: 80,
        handler: function() {
            fuelsensorstore.each(function(record) {
                record.set("choosed", true);
            });
        }
    });

    var btnSelectNone = new Ext.Button({
        text: _Photo_SelectNone,
        style: 'margin-right:16px',
        width: 80,
        handler: function() {
            fuelsensorstore.each(function(record) {
                record.set("choosed", false);
            });
        }
    });
    
    var btnGetSelected = new Ext.Button({
        text: _CommandExpression_ReadFuelSensor,
        style: 'margin-right:16px',
        width: 80,
        handler: function() {
            var sssidarray = [];
            var commandarray = [];
            var paramarray = [];
            fuelsensorstore.each(function(record) {
                if(record.get("choosed")){
                    var sssid = record.get("sssid");
                    sssidarray.push(sssid);
                    commandarray.push(EnumMT88Command.Get_Fuel_Sensor);
                    paramarray.push("");
                }
            });
            addTCPCommandWithDiffParamForMT(sssidarray,commandarray,paramarray);
        }
    });
    
            
   var tbar = new Ext.Toolbar({
        items: [
            _Alarm_TrackerName+':',
            trackNameCombo,
            {
                tooltip: { text: _TrackerMain_Search, autoHide: true },
                icon: 'images/search16.gif',
                handler: function() {
                    fuelsensorstore.reload({
                        params: {
                            sssids: trackNameCombo.getValue(),
                            start: 0,
                            limit: pagesize
                        }
                    });
                }
            },{
                xtype: 'tbseparator', width: 5
            },{
                tooltip:{text: _CustomerConfigResource_AddNew, autoHide: true },
                icon: 'images/add.png',
                handler: function() {
                   addnewfuelsensorwin();
                }
            },{
                tooltip:{text: _CustomerConfigResource_Delete, autoHide: true },
                icon: 'images/delete.png',
                handler: function() {
                    Ext.MessageBox.YESNO = { yes: _TrackerMain_Yes, no: _TrackerMain_No };
                    Ext.MessageBox.confirm(_TrackerMain_Title, _Photo_SureToDelete, function(btn){
                        if (btn == "yes") {
                            editor.stopEditing();
                            Ext.MessageBox.show({
                                msg: _CustomerConfigResource_Deleting,
                                progressText: _CustomerConfigResource_Deleting,
                                width: 300,
                                wait: true,
                                waitConfig: { interval: 200 }
                            });
      
                            var splitIds = "";
                            fuelsensorstore.each(function(record){
                                if(record.get('choosed')){
                                    if (splitIds.length =="") {
                                        splitIds = record.get("sssid");
                                    }
                                    else {
                                        splitIds += "," + record.get("sssid");
                                    }
                                }
                                
                            });
                            
                            Ext.Ajax.request({
                                url: 'HandlerDelFuelSensor',
                                success: function(result) {
                                    Ext.MessageBox.hide();
                                    var flag = eval(result.responseText);
                                    if (flag != "false") {
                                        fuelsensorstore.each(function(r){
                                            if(r.get('choosed'))
                                                fuelsensorstore.remove(r);
                                        });
                                        Ext.Msg.alert(_CustomerConfigResource_Tip, _CustomerConfigResource_Deleted);
                                    }
                                    else {
                                        Ext.Msg.alert(_CustomerConfigResource_Tip, _RouteResources_Failed);
                                    }
                                },
                                failure: function() {
                                    Ext.MessageBox.hide();
                                    Ext.Msg.alert(_CustomerConfigResource_Tip, _RouteResources_Failed);
                                },
                                params: {
                                    splitIds: splitIds,
                                    HandlerType: 'Delete'
                                }
                            })
                        }
                    });
                }
            }
       ]
   });
   
   var cmbfuelsensor = new Ext.form.ComboBox({
        typeAhead: true,
        triggerAction: 'all',
        lazyRender:true,
        forceSelection :true,
        mode: 'local',
        store: new Ext.data.ArrayStore({
            id: 0,
            fields: [
                'sensorid',
                'sensorname'
            ],
            data: [[0,_TrackerMain_Null],[1, _TrackerMain_FuelC], [2, _TrackerMain_FuelR],[3,_TrackerMain_FuelSensorV1]]
        }),
        valueField: 'sensorname',
        displayField: 'sensorname'
   });
   
   cmbfuelsensor.on('select',function(){
   });
   
   var choosebox = new Ext.form.Checkbox({
        allowBlank: true,
        maxLength:3
   });
   
   var checkFuelSensor = new Ext.grid.CheckColumn({
       header: '',
       width:25,
       sortable: false,
       dataIndex: 'choosed',
       editor:choosebox,
       fixed:true
    });
    
   var txttanksize = new Ext.form.NumberField({
        allowBlank: true,
        maxLength:3
   });
   
   var txtlowfuelpercent = new Ext.form.NumberField({
        allowBlank: false,
        blankText: _NewForText_CanNotEmpty,
        //emptyText:"0",
        maxLength:2,
        maxValue:99,
        minValue:0
   });
 
   var txthighfuelpercent = new Ext.form.NumberField({
        allowBlank: false,
        blankText: _NewForText_CanNotEmpty,
        //emptyText:"0",
        maxLength:2,
        maxValue:99,
        minValue:0
   });
   
   var btnQuickReport = new Ext.ux.grid.CellActions({
        iconIndex: 'btnQuickReport',
        qtipIndex: 'btnQuickReport'
    });
   

    
    var editor = new Ext.ux.grid.RowEditor({
        saveText: _CustomerConfigResource_Update,
        cancelText: _CustomerConfigResource_Cancel,
        listeners: {
            afteredit: function(object, changes, r, rowIndex) {
                
                // Make a simple save in your store (if you have a writer defined)
                //store.save();
                updateFuelSensor();
                // Do custom things
//                var cm = object.grid.colModel, fields = object.items.items;
//                for(var i = 0, len = cm.getColumnCount(); i < len; i++){
//                    var dindex = cm.getDataIndex(i);
//                    var value = fields[i].getValue();
//                              
//                }
//              
            }
        }
    });
    
    
    
    FuelSensorList.Grid = Ext.extend(Ext.grid.EditorGridPanel, {
        initComponent: function() {
            this.action = new Ext.ux.grid.RowActions({
                    header: ''
                      , autoWidth: true
                    , keepSelection: false
                    , actions: [{
                        iconCls: 'icon-quickly-report'
                        , qtip: _TrackerMain_QuickReport
                    }]
                    , callbacks: {
                        'icon-led-edit': function(grid, record, action, row, col) {

                        }
                    }
                });
             this.action.on({
                    action: function(grid, record, action, row, col) {
                       if (action == 'icon-quickly-report') {
                            calculateUnderTimeWindow(record.get('sssid'),0x01FF);
                        }
                    }
                });

            Ext.apply(this, {
                colModel: new Ext.grid.ColumnModel({
                    columns: [
                        checkFuelSensor,
                        {
                            header: _Alarm_Header_Name,
                            dataIndex: 'trackername',
                            width: 150
                        },{
                            header: _TrackerMain_FuelSensor,
                            dataIndex: 'fuel_sensor_name',
                            width: 150,
                            editor: cmbfuelsensor,
                            fixed:true
                        },
            //            {
            //                header: _TrackerMain_TankSize,
            //                dataIndex: 'tanksize',
            //                width: 100,
            //                editor: txttanksize,
            //                fixed:true
            //            },
                        {
                            header: _TrackerMain_LowFuelPercent,
                            dataIndex: 'low_alarm_percent',
                            width: 150,
                            editor:txtlowfuelpercent,
                            fixed:true
                        },
                        {
                            header: _TrackerMain_HighFuelPercent,
                            dataIndex: 'high_alarm_percent',
                            width: 150,
                            editor:txthighfuelpercent,
                            fixed:true
                        },{
                            header:_TrackerMain_LastUpdate,
                            dataIndex: 'lasttime',
                            width:120
                        },{
                            header:_TrackerMain_CurrentFuel,
                            dataIndex:'lastvalue',
                            width:80
                        },this.action

                    ],
                    defaults: {
                        sortable: true,
                        menuDisabled: true,
                        width: 25
                    }
                }),
                plugins: [checkFuelSensor, editor,this.action],
                viewConfig: { forceFit: true },
                stripeRows: true,
                //loadMask: true,
                listeners: {
                    load: { scope: this, fn: function() {
                        this.getSelectionModel().selectFirstRow();
                    }
                    }
                }
            });
            FuelSensorList.Grid.superclass.initComponent.apply(this, arguments);
        } //end function initComponent
        , onRender: function() {
            FuelSensorList.Grid.superclass.onRender.apply(this, arguments);

        } // eo function onRender
    });
    
    var grid = new FuelSensorList.Grid({
        store: fuelsensorstore,
        //cm:cm,
        stripeRows: true,
        loadMask: true,
        title: _TrackerMain_FuelSensorDefine,
        width:605,
        height:620,
        //plugins:[editor,checkFuelSensor],
        clicksToEdit: 2,
        selModel:new Ext.grid.RowSelectionModel({singleSelect : true})
    });

    grid.addListener("rowdblclick", function(grid, index) {
        
    });
    
    var fuelsensorwin = new Ext.Window({
        title: _TrackerMain_FuelSensorDefine,
        layout: 'fit',
        height: 490,
        width: 950,
        items: grid,
        tbar: tbar,
        iconCls:'icon-fuel',
        closeAction: 'close',
        minimizable: true,
        constrain:true,
        buttons:[btnSelectAll,btnSelectNone,btnGetSelected],
        listeners: {
            'minimize': function() {
                addTaskButtonForWindow(fuelsensorwin);
            }
        }
    });
    
    this.changeDisplay = function(sssid,data){
        var index = fuelsensorstore.findExact('sssid',sssid);
        if(index != -1){
            var record = fuelsensorstore.getAt(index);
            var tmp = data;
            record.set('fuel_sensor_name',sensorNameFromSensorId(parseInt(tmp[0])));
            record.set('high_alarm_percent',parseInt(tmp[1]));
            record.set('low_alarm_percent',parseInt(tmp[2]));
        }
      
    };
    
    this.changeFuelValue= function(sssid,time,fuelvalue){
        var index = fuelsensorstore.findExact('sssid',sssid);
        if(index != -1){
            var record = fuelsensorstore.getAt(index);
            record.set('lasttime',time);
            record.set('lastvalue',(fuelvalue*100).toFixed(2) + "%");
        }
    };
    
    fuelsensorstore.on('beforeload', function(store) {
        store.baseParams = {
            sssids: trackNameCombo.getValue(),
            start: 'start',
            limit: 'limit'
        }
    });
    
    
    function updateFuelSensor() {
        var record = grid.getSelectionModel().getSelections()[0];
        Ext.MessageBox.show({
            msg: _CustomerConfigResource_Saving,
            progressText: _CustomerConfigResource_Saving,
            width: 300,
            wait: true,
            waitConfig: { interval: 200 }
        });
        Ext.Ajax.request({
            url: 'HandlerUpdateFuelSensor',
            success: function(result) {
                Ext.MessageBox.hide();
                editor.stopEditing();
                var flag = eval(result.responseText);
                if (flag == true) {
                    msgUpdateSuccess();
                }
                else {
                    msgUpdateFailure();
                }
            },
            failure: function() {
                Ext.MessageBox.hide();
                msgUpdateFailure();
            },
            params: {
                id: record.data.id,
                sssid: record.data.sssid,
                fuel_sensor_id: sensorIdFromSensorName(record.data.fuel_sensor_name),
                low_alarm_percent: record.data.low_alarm_percent,
                high_alarm_percent: record.data.high_alarm_percent,
                tanksize:record.data.tanksize
            }
        })
       
    }

    //fuelsensorstore.on('update', updateFuelSensor);
        
    fuelsensorwin.show();
    
    fuelsensorwin.on('close',function(obj){
        g_FuelSensorWindowObject = null;
    });
    
    g_FuelSensorWindowObject = this;
}